package com.czxy.tanhua.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", filterName = "AppFilter")
public class AppFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 打印路径
        System.out.print(request.getMethod() + " ");
        System.out.print(request.getRequestURL() + " ");

        // 包装响应
        ResponseWrapper wrapperResponse = new ResponseWrapper(response);

        // 放行
        filterChain.doFilter(request,wrapperResponse);

        // 获得数据
        byte[] content = wrapperResponse.getContent();
        if(content.length <= 0) {
            System.out.println("无/404");
        } else {
            System.out.println(new String(content, "UTF-8"));

            //把返回值输出到客户端
            ServletOutputStream out = response.getOutputStream();
            out.write(content);
            out.flush();
        }
    }
}

class ResponseWrapper extends HttpServletResponseWrapper {

    // 用于缓存数据
    private ByteArrayOutputStream buffer;

    // 包装“缓存对象”，提供给servlet底层
    private ServletOutputStream out;

    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        buffer = new ByteArrayOutputStream();
        out = new ServletOutputStreamWrapper(buffer);
    }

    @Override
    public ServletOutputStream getOutputStream()
            throws IOException {
        return out;
    }

    @Override
    public void flushBuffer()
            throws IOException {
        if (out != null) {
            out.flush();
        }
    }

    public byte[] getContent()
            throws IOException {
        this.flushBuffer();
        return buffer.toByteArray();
    }
}

class ServletOutputStreamWrapper extends ServletOutputStream {
    private ByteArrayOutputStream bos;

    public ServletOutputStreamWrapper(ByteArrayOutputStream bos) {
        this.bos = bos;
    }

    @Override
    public void write(int b) throws IOException {
        bos.write(b);
    }

    @Override
    public boolean isReady() {
        return false;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
    }
}